<template>
  <div class="attendance-records">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ $t('attendance.records') }}</span>
        <div :class="{'header-actions': true, 'mobile-header-actions': isMobile}">
          <el-tooltip :content="$t('attendance.exportTooltip')" placement="top">
            <el-button 
              type="primary" 
              size="small" 
              @click="exportRecords" 
              :loading="exporting"
              class="export-button">
              <i class="el-icon-download"></i> <span class="button-text">{{ $t('attendance.exportRecords') }}</span>
            </el-button>
          </el-tooltip>
        </div>
      </div>
      
      <!-- 搜索条件 -->
      <div class="search-container">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <!-- 教师视图 -->
          <template v-if="viewMode === 'teacher' && (isTeacher || isAdmin)">
            <el-form-item :label="$t('course.title')">
              <el-select v-model="searchForm.courseId" :placeholder="$t('common.pleaseSelect') + ' ' + $t('course.title')" clearable>
                <el-option 
                  v-for="course in teacherCourses" 
                  :key="course.id" 
                  :label="course.name" 
                  :value="course.id">
                </el-option>
              </el-select>
            </el-form-item>
          </template>
          
          <!-- 学生视图 -->
          <template v-else>
            <el-form-item :label="$t('course.title')">
              <el-select v-model="searchForm.courseId" :placeholder="$t('common.pleaseSelect') + ' ' + $t('course.title')" clearable>
                <el-option 
                  v-for="course in studentCourses" 
                  :key="course.id" 
                  :label="course.name" 
                  :value="course.id">
                </el-option>
              </el-select>
            </el-form-item>
          </template>
          
          <el-form-item :label="$t('attendance.dateRange')">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              :range-separator="$t('common.to')"
              :start-placeholder="$t('attendance.startDate')"
              :end-placeholder="$t('attendance.endDate')"
              value-format="yyyy-MM-dd"
              @change="handleDateRangeChange">
            </el-date-picker>
          </el-form-item>
          
          <el-form-item :label="$t('attendance.status')">
            <el-select v-model="searchForm.status" :placeholder="$t('common.pleaseSelect') + ' ' + $t('attendance.status')" clearable>
              <el-option :label="$t('common.all')" :value="null"></el-option>
              <el-option :label="$t('attendance.normal')" :value="0"></el-option>
              <el-option :label="$t('attendance.late')" :value="1"></el-option>
              <el-option :label="$t('attendance.earlyLeave')" :value="2"></el-option>
              <el-option :label="$t('attendance.absent')" :value="3"></el-option>
              <el-option :label="$t('attendance.leave')" :value="4"></el-option>
              <el-option :label="$t('attendance.makeup')" :value="5"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="searchRecords">{{ $t('common.search') }}</el-button>
            <el-button @click="resetSearch">{{ $t('common.reset') }}</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 数据表格 -->
      <div class="table-container">
        <!-- 教师视图 -->
        <template v-if="viewMode === 'teacher' && (isTeacher || isAdmin)">
          <div class="batch-operations" style="margin-bottom: 10px;">
            <el-button 
              type="primary" 
              size="small" 
              @click="handleBatchOperation('normal')"
              :disabled="!selectedRecords.length">
              {{ $t('attendance.batchMarkNormal') }}
            </el-button>
            <el-button 
              type="warning" 
              size="small" 
              @click="handleBatchOperation('late')"
              :disabled="!selectedRecords.length">
              {{ $t('attendance.batchMarkLate') }}
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleBatchOperation('absent')"
              :disabled="!selectedRecords.length">
              {{ $t('attendance.batchMarkAbsent') }}
            </el-button>
            <el-button 
              type="primary" 
              size="small"
              plain 
              @click="handleBatchOperation('leave')"
              :disabled="!selectedRecords.length">
              {{ $t('attendance.batchMarkLeave') }}
            </el-button>
            <el-button 
              type="success" 
              size="small"
              plain 
              @click="handleBatchOperation('makeup')"
              :disabled="!selectedRecords.length">
              {{ $t('attendance.batchMarkMakeup') }}
            </el-button>
          </div>
          <el-table
            :data="tableData"
            border
            style="width: 100%"
            v-loading="loading"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="id" label="ID" width="80"></el-table-column>
            <el-table-column prop="userName" :label="$t('attendance.studentName')" width="120"></el-table-column>
            <el-table-column prop="courseName" :label="$t('attendance.courseName')" width="150"></el-table-column>
            <el-table-column prop="checkInTime" :label="$t('attendance.checkTime')" width="180"></el-table-column>
            <el-table-column :label="$t('attendance.status')" width="100">
              <template slot-scope="scope">
                <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="remark" :label="$t('common.remark')"></el-table-column>
            <el-table-column :label="$t('common.operation')" width="150" fixed="right" v-if="!isMobile">
              <template slot-scope="scope">
                <el-button 
                  type="primary" 
                  size="mini" 
                  @click="handleEdit(scope.row)"
                  :disabled="!isTeacher && !isAdmin">
                  {{ $t('common.edit') }}
                </el-button>
              </template>
            </el-table-column>
            <!-- 移动端操作列 -->
            <el-table-column :label="$t('common.operation')" width="95" fixed="right" v-if="isMobile">
              <template slot-scope="scope">
                <el-popover
                  placement="left"
                  width="120"
                  trigger="click">
                  <div class="mobile-operation-buttons">
                    <el-button 
                      type="primary" 
                      size="mini" 
                      @click="handleEdit(scope.row)"
                      :disabled="!isTeacher && !isAdmin">
                      {{ $t('common.edit') }}
                    </el-button>
                  </div>
                  <el-button slot="reference" type="primary" size="mini">
                    {{ $t('common.operation') }} <i class="el-icon-arrow-down"></i>
                  </el-button>
                </el-popover>
              </template>
            </el-table-column>
          </el-table>
        </template>
        
        <!-- 学生视图 -->
        <template v-else>
          <el-table
            :data="tableData"
            border
            style="width: 100%"
            v-loading="loading">
            <el-table-column prop="id" label="ID" width="80"></el-table-column>
            <el-table-column prop="courseName" :label="$t('attendance.courseName')" width="150"></el-table-column>
            <el-table-column prop="checkInTime" :label="$t('attendance.checkTime')" width="180"></el-table-column>
            <el-table-column :label="$t('attendance.status')" width="100">
              <template slot-scope="scope">
                <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="remark" :label="$t('common.remark')"></el-table-column>
          </el-table>
        </template>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pagination.pageSize"
            :layout="paginationLayout"
            :total="pagination.total">
          </el-pagination>
        </div>
      </div>
    </el-card>
    
    <!-- 编辑对话框 -->
    <el-dialog :title="$t('attendance.editRecord')" :visible.sync="editDialogVisible" width="500px" :fullscreen="isMobile">
      <el-form :model="editForm" label-width="100px" ref="editForm">
        <el-form-item :label="$t('attendance.studentName')">
          <span>{{ editForm.userName }}</span>
        </el-form-item>
        <el-form-item :label="$t('attendance.courseName')">
          <span>{{ editForm.courseName }}</span>
        </el-form-item>
        <el-form-item :label="$t('attendance.checkTime')">
          <span>{{ editForm.checkInTime }}</span>
        </el-form-item>
        <el-form-item :label="$t('attendance.status')" prop="status">
          <el-select v-model="editForm.status" :placeholder="$t('common.pleaseSelect') + ' ' + $t('attendance.status')">
            <el-option :label="$t('attendance.normal')" :value="0"></el-option>
            <el-option :label="$t('attendance.late')" :value="1"></el-option>
            <el-option :label="$t('attendance.earlyLeave')" :value="2"></el-option>
            <el-option :label="$t('attendance.absent')" :value="3"></el-option>
            <el-option :label="$t('attendance.leave')" :value="4"></el-option>
            <el-option :label="$t('attendance.makeup')" :value="5"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('common.remark')" prop="remark">
          <el-input v-model="editForm.remark" type="textarea" :rows="3"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="submitEdit" :loading="submitLoading">{{ $t('common.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 导入导出辅助工具
import { exportFile } from '@/utils/exportHelper';

export default {
  name: "AttendanceRecords",
  data() {
    return {
      viewMode: 'student', // 默认学生视图
      userInfo: JSON.parse(sessionStorage.getItem("userInfo")),
      isTeacher: false,
      isAdmin: false,
      loading: false,
      submitLoading: false,
      exporting: false, // 导出状态
      
      // 搜索表单
      searchForm: {
        studentId: null,
        courseId: null,
        startDate: null,
        endDate: null,
        status: null
      },
      dateRange: [],
      
      // 课程列表
      studentCourses: [],
      teacherCourses: [],
      
      // 表格数据
      tableData: [],
      
      // 分页
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      
      // 编辑对话框
      editDialogVisible: false,
      editForm: {
        id: null,
        courseId: null,
        userId: null,
        userName: '',
        courseName: '',
        checkInTime: '',
        status: 0,
        remark: ''
      },
      selectedRecords: [], // 选中的记录
      isMobile: false,
      screenWidth: document.body.clientWidth,
      paginationLayout: "total, sizes, prev, pager, next, jumper"
    }
  },
  created() {
    this.checkUserRole();
    this.initData();
    this.checkScreenSize();
  },
  mounted() {
    window.addEventListener('resize', this.handleResize);
    this.checkScreenSize();
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    handleResize() {
      this.screenWidth = document.body.clientWidth;
      this.checkScreenSize();
    },
    checkScreenSize() {
      this.isMobile = this.screenWidth < 768;
      
      // 根据屏幕尺寸调整分页控件布局
      if (this.isMobile) {
        this.paginationLayout = "prev, pager, next";
      } else {
        this.paginationLayout = "total, sizes, prev, pager, next, jumper";
      }
    },
    checkUserRole() {
      // 检查用户角色
      if (!this.userInfo) {
        console.error('用户信息不存在');
        this.$message.error('获取用户信息失败，请重新登录');
        return;
      }
      
      if (this.userInfo.roleName) {
        this.isTeacher = this.userInfo.roleName.includes('teacher');
        this.isAdmin = this.userInfo.roleName.includes('admin');
        
        // 如果是教师或管理员，默认使用教师视图
        if (this.isTeacher || this.isAdmin) {
          this.viewMode = 'teacher';
        }
      }
      
      // 设置默认学生ID
      this.searchForm.studentId = this.userInfo.userId;
    },
    initData() {
      if (!this.userInfo) {
        console.error('用户信息不存在，无法初始化数据');
        this.$message.error('获取用户信息失败，请重新登录');
        return;
      }
      
      // 如果是教师或管理员，先获取教师课程
      if (this.isTeacher || this.isAdmin) {
        this.getTeacherCourses();
      } else {
        // 否则获取学生课程
        this.getStudentCourses();
      }
      
      // 获取考勤记录
      this.searchRecords();
    },
    getStudentCourses() {
      const userId = this.userInfo ? this.userInfo.userId : null;
      if (!userId) {
        console.error('用户ID不存在，无法获取学生课程');
        this.$message.error('获取学生课程失败：用户信息不完整');
        return;
      }
      
      this.$axios.get(`/course/student/${userId}`).then(res => {
        if (res.code === 200) {
          this.studentCourses = res.data || [];
          //console.log('获取到学生课程列表:', this.studentCourses);
        }
      }).catch(err => {
        console.error('获取学生课程失败', err);
        this.$message.error('获取学生课程失败');
      });
    },
    getTeacherCourses() {
      const userId = this.userInfo ? this.userInfo.userId : null;
      
      if (!userId) {
        console.error('用户ID不存在，无法获取教师课程');
        this.$message.error('获取教师课程失败：用户信息不完整');
        return;
      }
      
      this.$axios.get(`/course/teacher/${userId}`).then(res => {
        if (res.code === 200) {
          this.teacherCourses = res.data || [];
          //console.log('获取到教师课程列表:', this.teacherCourses);
          
          // 如果是教师视图且有课程，自动选择第一个课程
          if (this.viewMode === 'teacher' && this.teacherCourses.length > 0) {
            this.searchForm.courseId = this.teacherCourses[0].id;
            this.searchRecords();
          }
        } else {
          this.$message.error(res.data.msg || '获取教师课程失败');
        }
      }).catch(err => {
        console.error('获取教师课程失败', err);
        this.$message.error('获取教师课程失败');
      });
    },
    handleDateRangeChange(val) {
      if (val) {
        this.searchForm.startDate = val[0];
        this.searchForm.endDate = val[1];
      } else {
        this.searchForm.startDate = null;
        this.searchForm.endDate = null;
      }
    },
    searchRecords() {
      this.loading = true;
      
      // 构建请求参数
      const params = {
        current: this.pagination.currentPage,
        size: this.pagination.pageSize,
        userId: this.viewMode === 'student' ? this.userInfo.id : null,
        courseId: this.searchForm.courseId,
        startDate: this.searchForm.startDate,
        endDate: this.searchForm.endDate,
        status: this.searchForm.status
      };
      
      // 移除空值
      Object.keys(params).forEach(key => {
        if (params[key] === null || params[key] === undefined) {
          delete params[key];
        }
      });
      
      //console.log('搜索参数:', params);
      
      this.$axios.get('/attendance/page', { params }).then(res => {
        if (res.code === 200) {
          const data = res.data;
          // 确保records是数组
          this.tableData = Array.isArray(data.records) ? data.records : [];
          this.pagination.total = data.total || 0;
          
          //console.log('获取到的考勤记录:', this.tableData);
          
          // 处理数据，添加课程名称和学生姓名
          if (this.tableData.length > 0) {
            this.processTableData();
          }
        } else {
          this.$message.error(res.data.msg || '获取考勤记录失败');
        }
      }).catch(err => {
        console.error('获取考勤记录失败', err);
        this.$message.error('获取考勤记录失败');
      }).finally(() => {
        this.loading = false;
      });
    },
    processTableData() {
      //console.log('开始处理表格数据');
      
      // 如果没有数据，直接返回
      if (!this.tableData || this.tableData.length === 0) {
        return;
      }
      
      // 获取所有课程ID和学生ID
      const courseIds = [...new Set(this.tableData.map(item => item.courseId))];
      const studentIds = [...new Set(this.tableData.map(item => item.userId))];
      
      //console.log('需要获取的课程ID:', courseIds);
      //console.log('需要获取的学生ID:', studentIds);
      
      // 创建一个Promise数组来存储所有请求
      const promises = [];
      
      // 添加课程信息请求
      if (courseIds.length > 0) {
        const coursePromises = courseIds.map(id => 
          this.$axios.get(`/course/detail/${id}`)
            .then(res => {
              if (res.code === 200 && res.data) {
                return { id, data: res.data };
              }
              return null;
            })
            .catch(err => {
              console.error(`获取课程ID ${id} 信息失败:`, err);
              return null;
            })
        );
        promises.push(...coursePromises);
      }
      
      // 添加学生信息请求（仅在教师视图时）
      if (this.viewMode === 'teacher' && (this.isTeacher || this.isAdmin) && studentIds.length > 0) {
        const studentPromises = studentIds.map(id =>
          this.$axios.get(`/user/${id}`)
            .then(res => {
              if (res.code === 200 && res.data) {
                return { id, data: res.data };
              }
              return null;
            })
            .catch(err => {
              console.error(`获取学生ID ${id} 信息失败:`, err);
              return null;
            })
        );
        promises.push(...studentPromises);
      }
      
      // 等待所有请求完成
      Promise.all(promises)
        .then(results => {
          // 过滤掉null结果
          const validResults = results.filter(result => result !== null);
          
          // 分离课程和学生信息
          const courseInfos = validResults.filter(result => result.data.name && !result.data.telephone);
          const studentInfos = validResults.filter(result => result.data.telephone);
          
          //console.log('获取到的课程信息:', courseInfos);
          //console.log('获取到的学生信息:', studentInfos);
          
          // 更新表格数据
          this.tableData = this.tableData.map(item => {
            const course = courseInfos.find(c => c.id === item.courseId);
            const student = studentInfos.find(s => s.id === item.userId);
            
            return {
              ...item, // 保留原始数据的所有字段
              courseName: course ? course.data.name : '未知课程',
              userName: student ? student.data.name : '未知学生',
              checkInTime: item.checkInTime ? new Date(item.checkInTime).toLocaleString() : ''
            };
          });
          
          //console.log('更新后的表格数据:', this.tableData);
        })
        .catch(err => {
          console.error('处理数据失败:', err);
          this.$message.error('获取详细信息失败');
        });
    },
    resetSearch() {
      this.searchForm = {
        studentId: this.userInfo.userId,
        courseId: null,
        startDate: null,
        endDate: null,
        status: null
      };
      this.dateRange = [];
      this.pagination.currentPage = 1;
      this.searchRecords();
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.searchRecords();
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.searchRecords();
    },
    getStatusType(status) {
      switch (status) {
        case 0: return 'success';  // 正常
        case 1: return 'warning';  // 迟到
        case 2: return 'info';     // 早退
        case 3: return 'danger';   // 旷课
        case 4: return 'primary';  // 请假
        case 5: return 'success';  // 补签
        default: return '';
      }
    },
    getStatusText(status) {
      switch (status) {
        case 0: return this.$t('attendance.normal');
        case 1: return this.$t('attendance.late');
        case 2: return this.$t('attendance.earlyLeave');
        case 3: return this.$t('attendance.absent');
        case 4: return this.$t('attendance.leave');
        case 5: return this.$t('attendance.makeup');
        default: return this.$t('common.unknown');
      }
    },
    handleEdit(row) {
      this.editForm = {
        id: row.id,
        courseId: row.courseId,
        userId: row.userId,
        userName: row.userName,
        courseName: row.courseName,
        checkInTime: row.checkInTime,
        status: row.status,
        remark: row.remark || ''
      };
      this.editDialogVisible = true;
    },
    submitEdit() {
      this.submitLoading = true;
      
      const params = {
        courseId: this.editForm.courseId,
        userId: this.editForm.userId,
        status: this.editForm.status,
        remark: this.editForm.remark,
        locationLatitude: 0,
        locationLongitude: 0
      };
      
      this.$axios.put(`/attendance/update/${this.editForm.id}`, params).then(res => {
        if (res.code === 200) {
          this.$message.success('修改成功');
          this.editDialogVisible = false;
          this.searchRecords(); // 重新加载数据
        } else {
          this.$message.error(res.data.msg || '修改失败');
        }
      }).catch(err => {
        console.error('修改失败', err);
        this.$message.error('修改失败');
      }).finally(() => {
        this.submitLoading = false;
      });
    },
    handleSelectionChange(val) {
      this.selectedRecords = val;
    },
    handleBatchOperation(type) {
      if (!this.selectedRecords.length) {
        this.$message.warning(this.$t('attendance.pleaseSelectRecords'));
        return;
      }
      
      const statusMap = {
        'normal': 0,
        'late': 1,
        'absent': 3,
        'leave': 4,
        'makeup': 5
      };
      
      const status = statusMap[type];
      
      this.$confirm(this.$t('attendance.batchConfirm', {status: this.getStatusText(status)}), this.$t('common.tip'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning'
      }).then(() => {
        // 创建批量更新的请求数组
        const updatePromises = this.selectedRecords.map(record => {
          const params = {
            courseId: record.courseId,
            userId: record.userId,
            status: status,
            remark: record.remark || '',
            locationLatitude: 0,
            locationLongitude: 0
          };
          return this.$axios.put(`/attendance/update/${record.id}`, params);
        });
        
        // 使用Promise.all等待所有请求完成
        Promise.all(updatePromises)
          .then(responses => {
            // 检查是否所有请求都成功
            const allSuccess = responses.every(res => res.code === 200);
            if (allSuccess) {
              this.$message.success(this.$t('attendance.batchUpdateSuccess'));
            } else {
              this.$message.warning(this.$t('attendance.batchUpdatePartial'));
            }
            this.searchRecords(); // 重新加载数据
          })
          .catch(err => {
            console.error('批量修改失败', err);
            this.$message.error(this.$t('attendance.batchUpdateFailed'));
          });
      }).catch(() => {
        // 用户取消操作，不做任何处理
      });
    },
    exportRecords() {
      // 构建查询参数
      const params = { ...this.searchForm };
      
      // 根据查看模式添加不同的筛选条件
      if (this.viewMode === 'teacher') {
        // 教师模式：添加教师ID
        params.teacherId = this.userInfo.id;
        
        // 如果未选择课程，提示选择
        if (!params.courseId) {
          this.$confirm('您想导出所有课程的考勤记录吗？', '导出确认', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.doExport(params);
          }).catch(() => {
            this.$message.info('已取消导出');
          });
        } else {
          this.doExport(params);
        }
      } else {
        this.doExport(params);
      }
    },
    doExport(params) {
      exportFile({
        url: '/attendance/export',
        params,
        defaultFileName: this.$t('attendance.records'),
        beforeExport: () => {
          this.exporting = true;
        },
        afterExport: () => {
          this.exporting = false;
        },
        fileType: 'csv',
        getCustomFileName: (params) => {
          // 生成自定义文件名
          const now = new Date();
          const dateStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
          let fileName = `${this.$t('attendance.records')}_${dateStr}`;
          
          // 如果指定了课程，添加课程名称
          if (params.courseId) {
            const course = this.viewMode === 'teacher' 
              ? this.teacherCourses.find(c => c.id === params.courseId)
              : this.studentCourses.find(c => c.id === params.courseId);
            
            if (course) {
              fileName += `_${course.name}`;
            }
          }
          
          // 如果指定了状态，添加状态名称
          if (params.status != null) {
            fileName += `_${this.getStatusText(params.status)}`;
          }
          
          return fileName;
        }
      });
    }
  },
  watch: {
    viewMode: {
      handler(newVal) {
        // 清空课程选择
        this.searchForm.courseId = null;
        
        // 根据视图模式获取相应的课程列表
        if (newVal === 'teacher' && (this.isTeacher || this.isAdmin)) {
          this.getTeacherCourses();
        } else {
          this.getStudentCourses();
        }
      },
      immediate: true
    }
  }
}
</script>

<style scoped>
.attendance-records {
  padding: 20px;
}

.search-container {
  margin-bottom: 20px;
}

.table-container {
  margin-top: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.batch-operations {
  margin-bottom: 10px;
}

.mobile-operation-buttons {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.mobile-operation-buttons .el-button {
  margin-left: 0;
  margin-bottom: 8px;
  width: 100%;
  text-align: left;
}

.mobile-operation-buttons .el-button:last-child {
  margin-bottom: 0;
}

/* 新增样式 */
.header-actions {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  float: right;
}

.mobile-header-actions {
  flex-direction: column;
  align-items: flex-end;
  float: none;
  margin-top: 10px;
}

.mobile-header-actions .export-button {
  width: 100%;
}

@media screen and (max-width: 768px) {
  .clearfix {
    display: flex;
    flex-direction: column;
  }
  
  .button-text {
    display: inline-block;
  }
  
  .export-button {
    margin-left: 0 !important;
    margin-top: 8px;
    width: 100%;
  }

  .search-container .el-form-item {
    display: block;
    width: 100%;
    margin-right: 0;
  }

  .search-container .el-select, 
  .search-container .el-date-editor {
    width: 100%;
  }

  .el-table {
    width: 100%;
    font-size: 12px;
  }
  
  .el-button {
    padding: 7px 10px;
    font-size: 12px;
  }

  .batch-operations {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }

  .batch-operations .el-button {
    margin-left: 0;
  }
}
</style> 